import PlaygroundSupport
import UIKit
var greeting = "Hello, playground发烧等撒灯撒灯"

let bgv = UIView(frame: CGRectMake(0, 0, 400, 400))
bgv.backgroundColor = .white
PlaygroundPage.current.liveView = bgv

let lb = customLabel(CGRectMake(0, 0, 100, 0), .red )
	//1.sizeToFit对于UILabel会考虑基线等因素,可能和2、3计算文字方法得到的结果稍有差异
lb.sizeToFit()
print(lb.frame) // "(0.0, 0.0, 87.0, 81.5)\n"

	//2.size(withAttributes)只能计算单行文字
(greeting as NSString).size(withAttributes: [.font: UIFont.systemFont(ofSize: 17)]) // {x 0 y 0 w 86.615 h 81.148}
																																										//3.boundingRect(with:options:attributes:context:)可以计算多行
let rect = (greeting as NSString).boundingRect(with: CGSizeMake(100, .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: UIFont.systemFont(ofSize: 17)], context: nil) //{x 0 y 0 w 86.615 h 81.148}

let lb2 = customLabel(CGRectMake(0, 0, 100, 0), .brown )
lb2.frame = CGRectMake(0, CGRectGetMaxY(lb.frame), rect.width, rect.height)

let lb3 = customLabel(CGRectMake(0, 0, 100, 0), .darkGray )
lb3.frame = CGRectMake(CGRectGetMaxX(lb.frame), CGRectGetMinY(lb.frame), rect.width, rect.height)

func customLabel(_ frame: CGRect,_ color: UIColor) -> UILabel {
	let lb3 = UILabel(frame: frame)
	lb3.text = greeting
	lb3.numberOfLines = 0
	bgv.addSubview(lb3)
	lb3.backgroundColor = color
	lb3.font = UIFont.systemFont(ofSize: 17)
	return lb3
}

	//结论:
	//1. size(withAttributes)只能计算单行文字尺寸
	//2. boundingRect(with:options:attributes:context:)可单行可多行
	//3. 单行时两者结果相同
	//4. sizeToFit在视图根据内容调整自身尺寸时使用,但在UILabel自适应自身文字时,会考虑基线、间距等情况，出现和上述两种计算文字得到的尺寸有偏差情况。但差别不大。
